package com.zbcz.crm.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.zbcz.crm.bean.Customer
import com.zbcz.crm.databinding.ItemSelectCustomerBinding

class CustomerSelectorAdapter :
    ListAdapter<Customer, CustomerSelectorAdapter.ViewHolder>(CustomerDiffCallback()) {

    // 添加数据集合的方法


    // 获取选中的客户
    fun getSelectedCustom(): Customer? {
        for (customer in currentList) {
            if (customer.isChecked) {
                return customer
            }
        }
        return null
    }

    inner class ViewHolder(private val binding: ItemSelectCustomerBinding) :
        RecyclerView.ViewHolder(binding.root) {

        init {
            binding.myCheckBox.setOnClickListener {
                val currentPosition = adapterPosition
                if (currentPosition != RecyclerView.NO_POSITION) {
                    // 取消之前选中的项目
                    for (i in currentList.indices) {
                        if (i != currentPosition && currentList[i].isChecked) {
                            currentList[i].isChecked = false
                            notifyItemChanged(i)
                        }
                    }
                    // 更新当前选中的项目
                    val currentCustomer = currentList[currentPosition]
                    currentCustomer.isChecked = !currentCustomer.isChecked
                    notifyItemChanged(currentPosition)
                }
            }
        }

        fun bind(customer: Customer) {
            val industryName = customer.customerIndustry?.let { getIndustryNameByValue(it) }
            val levelName = customer.customerLevel?.let { getCustomerLevelNameByValue(it) }
            val contentText =
                "${customer.customerName} ${customer.customerPhone}\n$industryName $levelName"
            binding.tvContent.text = contentText
            binding.myCheckBox.isSelected = customer.isChecked
            binding.ivDivider.visibility = if (adapterPosition != itemCount - 1) {
                ViewGroup.VISIBLE
            } else {
                ViewGroup.GONE
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding =
            ItemSelectCustomerBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    private val industriesMap = mapOf(
        "" to "请选择",
        "0" to "IT",
        "1" to "金融业",
        "2" to "房地产",
        "3" to "商业服务",
        "4" to "运输/物流",
        "5" to "生产",
        "6" to "政府",
        "7" to "文化传媒"
    )

    fun getIndustryNameByValue(value: String): String? {
        return industriesMap[value]
    }

    private val customerLevelsMap = mapOf(
        "" to "请选择",
        "0" to "重点客户",
        "1" to "普通客户",
        "2" to "非优先客户",
        "A" to "重点客户",
        "B" to "普通客户",
        "C" to "非优先客户"
    )

    fun getCustomerLevelNameByValue(value: String): String? {
        return customerLevelsMap[value]
    }

    private class CustomerDiffCallback : DiffUtil.ItemCallback<Customer>() {
        override fun areItemsTheSame(oldItem: Customer, newItem: Customer): Boolean {
            return oldItem.id == newItem.id // 这里根据你的 Customer 类的唯一标识来判断是否是同一个对象
        }

        override fun areContentsTheSame(oldItem: Customer, newItem: Customer): Boolean {
            return oldItem == newItem // 如果内容相同，就不需要刷新视图
        }
    }


    private var originalList: MutableList<Customer> = mutableListOf()
    private var filteredList: List<Customer> = listOf()

    init {
        // 初始化时，将原始数据赋值给原始列表和过滤列表
        originalList = currentList
        filteredList = currentList
    }

    // 添加数据集合的方法
    // 添加数据集合的方法
    fun submitData(data: List<Customer>) {
        originalList = data.toMutableList()
        filter("")
    }

    // 添加下一页数据的方法
    fun addNextPageData(data: List<Customer>) {
        val currentListSize = originalList.size
        originalList.addAll(data)
        filter("")  // 更新过滤后的列表
        notifyItemRangeInserted(currentListSize, data.size)
    }

    // 过滤数据
    fun filter(text: String) {
        filteredList = if (text.isEmpty()) {
            originalList
        } else {
            originalList.filter {
                it.customerName?.contains(text, ignoreCase = true) == true ||
                        it.customerPhone?.contains(text, ignoreCase = true) == true
            }
        }
        submitList(filteredList)
    }

}


